<template>
  <div class="container">
    <div class="titleBoxOut">
      <div class="titleBox clearfix">
        <span class="blockTitle">角色管理</span>
        <el-button
          type="primary"
          round
          class="listAddBtn fr"
          @click="addRole"
          v-show="
            this.$store.state.buttonLimitsArr.indexOf('roleManage:add') > -1
          "
          >新增角色</el-button
        >
      </div>
    </div>
    <div class="centerSection">
      <el-row class="searchBox searchInputWidth">
        <el-form :inline="true" :model="filterField">
          <el-form-item label="角色名称" class="row-padding-bottom">
            <el-input
              placeholder="请输入"
              clearable
              v-model="filterField.name"
              @blur="filterField.name = changeValue($event)"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchTable"
              class="commonBtn"
            ></el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <!-- 列表 -->
      <el-table
        :data="tableData"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        highlight-current-row
        stripe
        v-loading="loading"
        style="border: 1px solid #dfe6ec"
      >
        <el-table-column
          prop="name"
          label="角色名称"
          :formatter="formatTd"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="updateTime"
          label="最后修改日期"
          :formatter="formatTd"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          :formatter="formatTd"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="200px" align="left" fixed="right">
          <template slot-scope="scope">
            <!-- hasRoleUpdate:false,
      hasMenuUpdate:false,
      hasRoleDelet:false, -->
            <div v-if="hasRoleUpdate || hasMenuUpdate || hasRoleDelet">
              <el-link
                type="primary"
                @click="editRow(scope.row)"
                v-show="hasRoleUpdate"
                >编辑</el-link
              >
              <el-link
                type="primary"
                style="margin: 0 10px"
                @click="openMenuForm(scope.row)"
                v-show="hasMenuUpdate"
                >分配权限</el-link
              >
              <el-link
                type="primary"
                @click="toDeleteRow(scope.row)"
                v-show="hasRoleDelet"
                >删除</el-link
              >
            </div>
            <div v-else>
              <span>--</span>
            </div>
          </template>
        </el-table-column>
        <!-- 表格数据为空时，页面显示 -->
        <div slot="empty" v-show="isShow">
          <emptyTable emptyText="暂无相关信息"></emptyTable>
        </div>
      </el-table>
      <!-- filterField为搜索条件 -->
      <Pagination
        ref="pagination"
        @getList="getTableList"
        :requestUrl="requestUrl"
        :filterField="filterField"
      ></Pagination>
    </div>

    <!--添加，编辑角色-->
    <el-dialog
      :title="addOrEdit == 0 ? '添加角色' : '编辑角色'"
      :visible.sync="formVisible"
      :close-on-click-modal="false"
      @close="handleCloseForm"
      custom-class="dialog-minwidth"
      :modal-append-to-body="false"
    >
      <el-form
        :model="formData"
        label-width="80px"
        :rules="formRules"
        ref="formData"
        class="form"
      >
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item label="角色名称" prop="name">
              <el-input
                v-model="formData.name"
                placeholder="请输入角色名称"
                @blur="formData.name = changeValue($event)"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item label="备注说明">
              <el-input
                type="textarea"
                placeholder="请输入备注说明"
                v-model="formData.remark"
                maxlength="200"
                rows="6"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="handleCloseForm" class="cancel"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click.native="toSave"
          class="save"
          :loading="isRuleLoading"
          >确认</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="分配权限"
      :visible.sync="menuFormVisible"
      :close-on-click-modal="false"
      @close="handleCloseMenuForm"
      custom-class="dialog-minwidth"
      :modal-append-to-body="false"
    >
      <el-form
        :model="menuFormData"
        label-width="80px"
        :rules="menuFormRules"
        ref="menuForm"
        class="form"
      >
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item label="分配菜单" prop="menuAssignment">
              <div class="treeBox clearfix">
                <el-col :span="24" class="col-position tree">
                  <el-tree
                    :data="data"
                    show-checkbox
                    node-key="id"
                    @check-change="handleCheckChange"
                    default-expand-all
                    :default-checked-keys="selectedMenu"
                    ref="tree"
                    :props="defaultProps"
                  ></el-tree>
                </el-col>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="handleCloseMenuForm" class="cancel"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click.native="toSaveMenu"
          class="save"
          :loading="isMenuLoading"
          >确认</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'roleManage',
  components: {},
  data() {
    var checkMenuAssignment = (rule, value, callback) => {
      var that = this

      if (that.selectedMenu.length == 0) {
        return callback(new Error('请选择分配菜单'))
      } else {
        callback()
      }
    }
    return {
      requestUrl: 'api-u/rolelist', //表格请求路径
      tableData: [],
      filterField: {
        name: '',
      },
      formVisible: false, //弹窗的显示隐藏
      formData: {
        //弹窗中的数据
        name: '',
        remark: '',
      },
      //验证
      formRules: {
        name: [
          {
            required: true,
            pattern: /^[\s\S]*.*[^\s][\s\S]*$/,
            message: '请输入角色名称',
            trigger: 'blur',
          },
        ],
      },
      menuFormVisible: false,
      menuFormRules: {
        menuAssignment: [
          {
            required: true,
            validator: checkMenuAssignment,
            trigger: 'change',
          },
        ],
      },
      menuFormData: {
        id: '',
      },
      data: [],
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      expandOnClick: false,
      // 默认选中的节点
      selectedMenu: [],
      addOrEdit: 0,
      // 添加角色loading
      isRuleLoading: false,
      // 权限loading
      isMenuLoading: false,
      loading: true,
      isShow: false,
      //权限按钮
      hasRoleUpdate: false,
      hasMenuUpdate: false,
      hasRoleDelet: false,
    }
  },
  created() {
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
    // 判断按钮权限
    this.hasRoleUpdate =
      this.$store.state.buttonLimitsArr.indexOf('roleManage:update') > -1
    this.hasMenuUpdate =
      this.$store.state.buttonLimitsArr.indexOf('roleManage:update') > -1
    this.hasRoleDelet =
      this.$store.state.buttonLimitsArr.indexOf('roleManage:delete') > -1
  },
  methods: {
    getTableList(data) {
      this.tableData = data
      this.loading = false
      if (this.tableData.length < 1) {
        this.isShow = true
      }
    },
    //列表查询
    searchTable() {
      this.$refs.pagination.getTableListData()
    },
    //点击添加角色
    addRole() {
      this.formVisible = true
      this.addOrEdit = 0
      this.formData = {
        //弹窗中的数据
        name: '',
        remark: '',
      }
    },
    handleCloseForm() {
      this.formVisible = false
      this.$refs['formData'].resetFields()
    },
    // 关闭弹窗
    closeDialog() {},
    // 选中菜单
    handleCheckChange() {
      var res = this.$refs.tree.getCheckedKeys()
      this.selectedMenu = res
    },
    // 点击弹窗中的保存
    toSave() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.save()
        } else {
          console.log('验证未通过')
        }
      })
    },
    save() {
      var way = ''
      if (this.addOrEdit == 0) {
        way = 'post'
      } else {
        way = 'put'
      }
      this.isRuleLoading = true
      this.axios({
        method: way,
        url: 'api-u/roles',
        data: this.formData,
      })
        .then(
          (response) => {
            this.isRuleLoading = false
            if (!response.data.hasError) {
              this.$message({
                message: '添加成功',
                type: 'success',
              })
              this.formVisible = false
              this.$refs.pagination.getTableListData()
            } else {
              this.$message({
                message: response.data.msg,
                type: 'error',
              })
            }
          },
          (response) => {
            this.isRuleLoading = false
            this.$message({
              message: '数据请求失败',
              type: 'error',
            })
          }
        )
        .catch((error) => {
          this.isRuleLoading = false
        })
    },
    //删除
    toDeleteRow(row) {
      this.$confirm('是否确认删除此角色?', '删除角色', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.deleteRow(row)
        })
        .catch(() => {})
    },
    deleteRow(row) {
      this.axios({
        method: 'delete',
        url: 'api-u/roles/' + row.id,
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.$message({
                message: '删除成功',
                type: 'success',
              })
              this.$refs.pagination.getTableListData()
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    getMetree() {
      this.axios({
        method: 'get',
        url: 'api-m/menus/metree',
      })
        .then(
          (response) => {
            this.data = []
            this.data = response.data
          },
          (response) => {
            this.$message({
              message: '数据请求失败，请重试',
              type: 'error',
            })
          }
        )
        .catch((error) => {})
    },
    openMenuForm(row) {
      this.menuFormVisible = true
      this.menuFormData.id = row.id
      this.getMetree()
      this.getMenus(row)
    },
    handleCloseMenuForm() {
      this.menuFormVisible = false
      this.$refs['menuForm'].resetFields()
    },
    getMenus(row) {
      this.axios({
        method: 'get',
        url: 'api-m/menus?roleId=' + row.id,
      })
        .then(
          (response) => {
            this.selectedMenu = []
            this.selectedMenu = response.data
          },
          (response) => {
            this.$message({
              message: '数据请求失败，请重试',
              type: 'error',
            })
          }
        )
        .catch((error) => {})
    },
    editRow(row) {
      this.addOrEdit = 1
      this.formVisible = true
      this.formData = {
        //弹窗中的数据
        name: row.name,
        remark: row.remark,
        id: row.id,
      }
    },
    toSaveMenu() {
      this.$refs.menuForm.validate((valid) => {
        if (valid) {
          this.saveMenu()
        } else {
        }
      })
    },
    saveMenu() {
      this.isMenuLoading = true
      this.axios({
        method: 'post',
        url: 'api-m/menus/managetoRole',
        data: {
          roleId: this.menuFormData.id,
          menuIds: this.selectedMenu.join(','),
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.$message({
                message: '分配权限成功',
                type: 'success',
              })
              this.$refs.pagination.getTableListData()
              this.menuFormVisible = false
              this.isMenuLoading = false
            } else {
              this.isMenuLoading = false
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {
            this.isMenuLoading = false
            this.$message({
              message: '数据请求失败，请重试',
              type: 'error',
            })
          }
        )
        .catch((error) => {
          this.isMenuLoading = false
        })
    },
  },
}
</script>

<style scoped lang="less">
.el-button--primary {
  color: #fff;
  background: #009588;
  border-color: #009588;
}
.container {
  position: absolute;
  top: 130px;
  left: 24px;
  right: 24px;
  bottom: 24px;
  background: #fff;
  overflow: hidden;
  //overflow-y: auto;
  .titleBoxOut {
    padding: 0 24px;
    background: #fff;
  }
  .titleBox {
    border-bottom: 1px solid #e3e7e9;
    padding: 14px 0;
    margin-bottom: 0px;
    position: relative;
    .listAddBtn {
      position: absolute;
      right: 16px;
      top: 8px;
      width: 136px;
      line-height: 34px;
      height: 34px;
      padding: 0;
      background: #009588;
      border: none;
    }

    .blockTitle {
      font-weight: bold;
      font-size: 18px;
      color: #333;
      line-height: 22px;
    }
  }
  .centerSection {
    padding: 24px;
    position: absolute;
    overflow-y: auto;
    left: 0;
    bottom: 0;
    right: 0;
    top: 68px;
  }
}

.treeBox {
  background: #f5f7fa;
  border: 1px solid #dee5f4;
  border-radius: 4px;
  padding: 12px;
  .tree {
    height: 235px;
    overflow-y: auto;
    .el-tree {
      background: #f5f7fa;
    }
  }
}
</style>
